package com.century.sjt.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.Constant;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.SjtModel;
import com.century.sjt.EMChat.db.InviteMessgeDao;
import com.century.sjt.EMChat.db.UserDao;
import com.century.sjt.activity.login.LoginActivity;
import com.century.sjt.domain.InviteMessage;
import com.century.sjt.entity.Merchant;
import com.century.sjt.EMChat.fragment.ContactListFragment;
import com.century.sjt.EMChat.fragment.ConversationListFragment;
import com.century.sjt.fragment.FragmentHome;
import com.century.sjt.fragment.FragmentDiscover;
import com.century.sjt.util.BaiduTranslate;
import com.century.sjt.util.TipUtil;
import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.century.sjt.EMChat.domain.Translate;
import com.century.sjt.EMChat.widget.EaseAlertDialog;
import com.easemob.util.EMLog;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity implements EMEventListener, View.OnClickListener{
//    master

    protected static final String TAG = "MainActivity";
    private FrameLayout mLayout_1;
    private FrameLayout mLayout_2;
    private FrameLayout mLayout_3;
    private FrameLayout mLayout_4;

    private TextView iconHome,iconMessage,iconMail,iconDiscover;
    private TextView tvHome,tvMessage,tvMail,tvDiscover;


    private FragmentHome mFragment_1;
    private ConversationListFragment mFragment_2;
    private ContactListFragment mFragment_3;
    private FragmentDiscover mFragment_4;

    private SjtModel settingsModel;
    private int index;
    // 当前fragment的index
    private int currentTabIndex;
    // 账号在别处登录
    public boolean isConflict = false;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;

    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;

    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;
    private BroadcastReceiver internalDebugReceiver;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;

    private BaiduTranslate baiduTranslate;

    private TextView unreadLabel,unreadAddressLable;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initEvent();
        setSelect(0);

        settingsModel = SjtHelper.getInstance().getModel();
        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            SjtHelper.getInstance().logout(true, null);
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            finish();
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }

        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);

        // 注册群组和联系人监听
        SjtHelper.getInstance().registerGroupAndContactListener();
        registerBroadcastReceiver();


        //内部测试方法，请忽略
        registerInternalDebugReceiver();
        Intent intent = getIntent();
        //选中meFrogment
//        onTabClicked(mTabs[4]);
//
//        if (intent.getStringExtra("id")==null||"".equals(intent.getStringExtra("id"))){
//            intoID = intent.getStringExtra("id");
//            onTabClicked(mTabs[0]);
//        }else {
//            onTabClicked(mTabs[4]);
//        }

        //蒲公英
        //在 activity 中集成，可以有机会捕捉更多的异常（推荐）
//        PgyUpdateManager.register(this);//检查更新
        PgyCrashManager.register(this);
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {

                    @Override
                    public void onUpdateAvailable(final String result) {

                        // 将新版本信息封装到AppBean中
//                        Log.e("result",result.toString());

                        final AppBean appBean = getAppBeanFromString(result);
                        String versionCode = appBean.getVersionCode();
                        String versionName = appBean.getVersionName();
                        final String url = appBean.getDownloadURL();
                        String releaseNote = appBean.getReleaseNote();
                        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                                .setCancelable(false)
                                .show();
                        Window window = alertDialog.getWindow();
                        window.setContentView(R.layout.sjt_update_alertdialog);
                        TextView tv_title = (TextView) window.findViewById(R.id.tv_dialog_title);
                        tv_title.setText("世纪通更新");
                        TextView tv_message = (TextView) window.findViewById(R.id.tv_dialog_message);
                        tv_message.setText(releaseNote);
                        Button btn_submit = (Button) window.findViewById(R.id.btn_dialog_submit);
                        btn_submit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startDownloadTask(MainActivity.this, url);
                            }
                        });

                    }

                    @Override
                    public void onNoUpdateAvailable() {
                    }
                });

        MyBaiduTranslate();
    }

    public void setSelectOrder(){
        resetImgs();
        setSelect(1);
    }
    public RequestQueue getQueue(){
        return this.mQueue;
    }

    @Override
    protected void initView() {
        unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
        unreadAddressLable = (TextView) findViewById(R.id.unread_address_number);
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        mLayout_1 = (FrameLayout)findViewById(R.id.linearlayout_1);
        mLayout_2 = (FrameLayout)findViewById(R.id.linearlayout_2);
        mLayout_3 = (FrameLayout)findViewById(R.id.linearlayout_3);
        mLayout_4 = (FrameLayout)findViewById(R.id.linearlayout_4);
        iconHome = (TextView) findViewById(R.id.icon_home);
        iconMessage = (TextView) findViewById(R.id.icon_message);
        iconMail = (TextView) findViewById(R.id.icon_mail);
        iconDiscover = (TextView) findViewById(R.id.icon_discover);
        iconHome.setTypeface(iconfont);
        iconMessage.setTypeface(iconfont);
        iconMail.setTypeface(iconfont);
        iconDiscover.setTypeface(iconfont);
        tvHome = (TextView) findViewById(R.id.text_home);
        tvMessage = (TextView) findViewById(R.id.text_message);
        tvMail = (TextView) findViewById(R.id.text_mail);
        tvDiscover = (TextView) findViewById(R.id.text_discover);

    }

    @Override
    protected void initEvent() {
        mLayout_1.setOnClickListener(this);
        mLayout_2.setOnClickListener(this);
        mLayout_3.setOnClickListener(this);
        mLayout_4.setOnClickListener(this);
        setSelect(0);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void setSelect(int i) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);
        switch (i) {
            case 0:
                if (mFragment_1 == null) {
                    mFragment_1 = new FragmentHome();
                    transaction.add(R.id.id_content, mFragment_1);
                } else {
                    transaction.show(mFragment_1);
                }

                iconHome.setTextColor(getResources().getColor(R.color.textdefault_main));
                tvHome.setTextColor(getResources().getColor(R.color.textdefault_main));
                break;
            case 1:
                if (mFragment_2 == null) {
                    mFragment_2 = new ConversationListFragment();
                    transaction.add(R.id.id_content, mFragment_2);
                } else {
                    transaction.show(mFragment_2);
                }
                iconMessage.setTextColor(getResources().getColor(R.color.textdefault_main));
                tvMessage.setTextColor(getResources().getColor(R.color.textdefault_main));
                break;
            case 2:
                if (mFragment_3 == null) {
                    mFragment_3 = new ContactListFragment();
                    transaction.add(R.id.id_content, mFragment_3);
                } else {
                    transaction.show(mFragment_3);
                }
                iconMail.setTextColor(getResources().getColor(R.color.textdefault_main));
                tvMail.setTextColor(getResources().getColor(R.color.textdefault_main));
                break;
            case 3:
                if (mFragment_4 == null) {
                    mFragment_4 = new FragmentDiscover();
                    transaction.add(R.id.id_content, mFragment_4);
                } else {
                    transaction.show(mFragment_4);
                }
                iconDiscover.setTextColor(getResources().getColor(R.color.textdefault_main));
                tvDiscover.setTextColor(getResources().getColor(R.color.textdefault_main));
                break;
            default:
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (mFragment_1 != null)
            transaction.hide(mFragment_1);
        if (mFragment_2 != null)
            transaction.hide(mFragment_2);
        if (mFragment_3 != null)
            transaction.hide(mFragment_3);
        if (mFragment_4 != null)
            transaction.hide(mFragment_4);
    }

    @Override
    public void onClick(View v) {
        resetImgs();
        switch (v.getId()) {
            case R.id.linearlayout_1:
                setSelect(0);
                break;
            case R.id.linearlayout_2:
                setSelect(1);
                break;
            case R.id.linearlayout_3:
                setSelect(2);
                break;
            case R.id.linearlayout_4:
                setSelect(3);
                break;
            default:
        }
    }

    private void resetImgs() {
        iconHome.setTextColor(getResources().getColor(R.color.textdefault_line));
        tvHome.setTextColor(getResources().getColor(R.color.textdefault_line));
        iconMessage.setTextColor(getResources().getColor(R.color.textdefault_line));
        tvMessage.setTextColor(getResources().getColor(R.color.textdefault_line));
        iconMail.setTextColor(getResources().getColor(R.color.textdefault_line));
        tvMail.setTextColor(getResources().getColor(R.color.textdefault_line));
        iconDiscover.setTextColor(getResources().getColor(R.color.textdefault_line));
        tvDiscover.setTextColor(getResources().getColor(R.color.textdefault_line));
    }

    /**
     * 监听事件
     */
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage: // 普通消息
            {
                EMMessage message = (EMMessage) event.getData();
//                Log.e("message",message.getBody().toString());
                int type = message.getType().ordinal();
                // 提示新消息
                SjtHelper.getInstance().getNotifier().onNewMsg(message);
                refreshUIWithMessage();
                if (settingsModel.getSettingBaiTranslate()){
                    if (type == EMMessage.Type.TXT.ordinal()){
                        String Username =SjtHelper.getInstance(). getCurrentUsernName();
                        String language = message.getStringAttribute("language",null);
                        if (null==language||"".equals(language)){

                        }else {
//                            Log.e("for",message.getFrom().toString());
//                            Log.e("to",message.getTo().toString()+"###"+Username);
                            if (message.getTo().equals(Username)){
                                baiduTranslate.translate(MainActivity.this,mQueue,message, "zh", "en");
                            }
                        }

                    }
                }
                break;
            }

            case EventOfflineMessage: {
                EMLog.d(TAG, "received offline messages");
                EMMessage message = null;
                List<EMMessage> messages = (List<EMMessage>) event.getData();
                refreshUIWithMessage();
                //离线消息翻译
                if (settingsModel.getSettingBaiTranslate()){
                    for (int i = 0;i<messages.size();i++){
                        message = messages.get(i);
                        int type = message.getType().ordinal();
                        if (type == EMMessage.Type.TXT.ordinal()){
                            String Username =SjtHelper.getInstance(). getCurrentUsernName();
                            String language = message.getStringAttribute("language",null);
                            if (null==language||"".equals(language)){

                            }else {
                                if (message.getTo().equals(Username)){
                                    baiduTranslate.translate(MainActivity.this,mQueue,message, "zh", "en");
                                }
                            }

                        }
                    }

                }

                break;
            }

            case EventConversationListChanged: {
                EMMessage message = null;
                List<EMMessage> messages = (List<EMMessage>) event.getData();
                refreshUIWithMessage();
                //推送消息翻译
                if (settingsModel.getSettingBaiTranslate()){
                    for (int i = 0;i<messages.size();i++){
                        message = messages.get(i);
                        int type = message.getType().ordinal();
                        if (type == EMMessage.Type.TXT.ordinal()){
                            String Username =SjtHelper.getInstance(). getCurrentUsernName();
                            String language = message.getStringAttribute("language",null);
                            if (null==language||"".equals(language)){

                            }else {
                                if (message.getTo().equals(Username)){
                                    baiduTranslate.translate(MainActivity.this,mQueue,message, "zh", "en");
                                }
                            }

                        }
                    }

                }

                break;
            }

            default:
                break;
        }
    }

    public void MyBaiduTranslate(){
        baiduTranslate = new BaiduTranslate();
        baiduTranslate.setTranslateListItemClickListener(new BaiduTranslate.TranslateListItemClickListener() {
            @Override
            public void onSaveClick(Translate message) {
//                listener.onSaveClick(message);
            }

            @Override
            public void onUpdateClick(Translate message) {
            }

            @Override
            public void onDeleteClick(Translate message) {
            }
        });
    }
    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // 刷新bottom bar消息未读数
                updateUnreadLabel();
                if (currentTabIndex == 1) {
                    // 当前页面如果为聊天历史页面，刷新此页面
                    if (mFragment_2 != null) {
                        mFragment_2.refresh();
                    }
                }
            }
        });
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
                updateUnreadAddressLable();
                if (currentTabIndex == 1) {
                    // 当前页面如果为聊天历史页面，刷新此页面
                    if (mFragment_2 != null) {
                        mFragment_2.refresh();
                    }
                } else if (currentTabIndex == 2) {
                    if (mFragment_3 != null) {
                        mFragment_3.refresh();
                    }
                } else if (currentTabIndex == 0) {
                    if (mFragment_1 != null) {
                        mFragment_1.updateUnreadAddressLable();
                    }
                }
                String action = intent.getAction();
//                if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
//                    if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
//                        GroupsActivity.instance.onResume();
//                    }
//                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
        unregisterBroadcastReceiver();

        try {
            unregisterReceiver(internalDebugReceiver);
        } catch (Exception e) {
        }
    }

    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            unreadLabel.setText(String.valueOf(count));
            unreadLabel.setVisibility(View.VISIBLE);
        } else {
            unreadLabel.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 刷新申请与通知消息数
     */
    public void updateUnreadAddressLable() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadAddressCountTotal();
                if (count > 0) {
					unreadAddressLable.setText(String.valueOf(count));
                    unreadAddressLable.setVisibility(View.VISIBLE);
                } else {
                    unreadAddressLable.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    /**
     * 获取未读申请与通知消息
     *
     * @return
     */
    public int getUnreadAddressCountTotal() {
        int unreadAddressCountTotal = 0;
        unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
        return unreadAddressCountTotal;
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        for (EMConversation conversation : EMChatManager.getInstance().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }


    /**
     * 保存提示新消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // 提示有新消息
        SjtHelper.getInstance().getNotifier().viberateAndPlayTone(null);

        // 刷新bottom bar消息未读数
        updateUnreadAddressLable();
        // 刷新好友页面ui
        if (currentTabIndex == 2)
            mFragment_3.refresh();
    }

    /**
     * 保存邀请等msg
     *
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // 保存msg
        inviteMessgeDao.saveMessage(msg);
        //保存未读数，这里没有精确计算
        inviteMessgeDao.saveUnreadMessageCount(1);
    }

    //是否登录
    private void isLogin(){


        SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        String isLogin = mainSharedPreferences.getString("isLogin", "");
        if(isLogin.equals("0")){
            logout();
        }
    }

    private void cleanInfo() {
        SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mainSharedPreferences.edit();
        editor.clear();
        editor.putString("isLogin", "0");
        editor.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();

        isLogin();//是否登录

        if (!isConflict && !isCurrentAccountRemoved) {
            updateUnreadLabel();
            updateUnreadAddressLable();
        }
        // unregister this event listener when this activity enters the
        // background
        SjtHelper sdkHelper = SjtHelper.getInstance();
        sdkHelper.pushActivity(this);

        // register the event listener when enter the foreground
        EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
    }

    @Override
    protected void onStop() {
        EMChatManager.getInstance().unregisterEventListener(this);
        SjtHelper sdkHelper = SjtHelper.getInstance();
        sdkHelper.popActivity(this);

        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        SjtHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        conflictBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
            }

        }

    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        SjtHelper.getInstance().logout(true, null);
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage(R.string.text_remote_login);
                accountRemovedBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        accountRemovedBuilder = null;
                        finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color userRemovedBuilder error" + e.getMessage());
            }

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }
    }

    /**
     * 内部测试代码，开发者请忽略
     */
    private void registerInternalDebugReceiver() {
        internalDebugReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                SjtHelper.getInstance().logout(true, new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                // 重新显示登陆页面
                                finish();
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));

                            }
                        });
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(int code, String message) {
                    }
                });
            }
        };
        IntentFilter filter = new IntentFilter(getPackageName() + ".em_internal_debug");
        registerReceiver(internalDebugReceiver, filter);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
//        getMenuInflater().inflate(R.menu.context_tab_contact, menu);
    }

    private void logout() {
        final ProgressDialog pd = new ProgressDialog(MainActivity.this);
        String st = getResources().getString(R.string.Are_logged_out);
        pd.setMessage(st);
        pd.setCanceledOnTouchOutside(false);
        pd.show();
        SjtHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        // 清空本地用户信息
                        cleanInfo();
                        // 重新显示登陆页面
                        (MainActivity.this).finish();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));

                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        pd.dismiss();
                        Toast.makeText(MainActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();


                    }
                });
            }
        });
    }

    //加载好友信息
    public void qrRecordCodeResult(int requestCode, int resultCode, Intent data){
        switch (requestCode) {
            case com.century.sjt.util.Constant.SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
//                    Toast.makeText(SjtMainActivity.this, bundle.getString("result"), Toast.LENGTH_LONG).show();
                    String result = bundle.getString("result");
                    //判断返回字符串数据是打开网页还是加好友
                    if(result.indexOf(com.century.sjt.util.Constant.QRRECORD_ADDFRIEND)>=0) {
                        //判断“：”前后的字符串
                        int i = result.indexOf(':');
//                  int x = mQRCordId.indexOf(':',i+1);
                        String option = result.substring(0, i);
                        String friendId = result.substring(i + 1);
                        switch (option) {
                            case com.century.sjt.util.Constant.QRRECORD_ADDFRIEND:
                                qrAddfrind(friendId);
                                break;
                            default:
                                break;
                        }
                    }else if(result.indexOf(com.century.sjt.util.Constant.QRRECORD_SHOP_ID)>=0) {//扫描商家二维码
//                        商家身份暂不支持支付
                        String isShop = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE).getString("isShop", "");
                        if("0".equals(isShop)) {
                            //判断“：”前后的字符串
                            int i = result.indexOf(':');
//                          int x = mQRCordId.indexOf(':',i+1);
                            String option = result.substring(0, i);
                            String shopId = result.substring(i + 1);
                            switch (option) {
                                case com.century.sjt.util.Constant.QRRECORD_SHOP_ID:
                                    shopDetail(shopId);
                                    break;
                                default:
                                    break;
                            }
                        }else {
                            TipUtil.showToast("商家身份暂不支持支付", MainActivity.this, 1);
                        }
                    }else if(result.indexOf(com.century.sjt.util.Constant.QRRECORD_HTTP)>=0) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(result));
                        startActivity(intent);
                    }else{
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse("https://www.baidu.com/s?wd=" + result));
                        startActivity(intent);
                    }

//                    mTextView.setText(bundle.getString("result"));
//                    mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                }
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        qrRecordCodeResult(requestCode,resultCode,data);
    }

    private void qrAddfrind(final String addfriendId) {

        if(EMChatManager.getInstance().getCurrentUser().equals(addfriendId)){
            new EaseAlertDialog(MainActivity.this, R.string.not_add_myself).show();
            return;
        }

        if(SjtHelper.getInstance().getContactList().containsKey(addfriendId)){
//            提示已在好友列表中(在黑名单列表里)，无需添加
//            if(EMContactManager.getInstance().getBlackListUsernames().contains(addfriendId)){
//                new EaseAlertDialog(MainActivity.this, R.string.user_already_in_contactlist).show();
//                return;
//            }
            new EaseAlertDialog(MainActivity.this, R.string.This_user_is_already_your_friend).show();
            return;
        }

        progressDialog = new ProgressDialog(MainActivity.this);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    //demo写死了个reason，实际应该让用户手动填入
                    String s = getResources().getString(R.string.Add_a_friend);
                    EMContactManager.getInstance().addContact(addfriendId, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(R.string.send_successful);
                            TipUtil.showToast(s1, MainActivity.this, 1);
//                            Toast.makeText(getApplicationContext(), s1, 1).show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                            TipUtil.showToast(s2 + e.getMessage(), MainActivity.this, 1);
//                            Toast.makeText(getApplicationContext(), s2 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();

    }


    /**
     * 获取商店详情
     * @param shopId
     */
    private void shopDetail(final String shopId) {
        TipUtil.openProgressDialog(com.century.sjt.util.Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MainActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.ShopDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        merchant.setUserId(aData.getString("userId"));
                        merchant.setLastTopic(aData.getString("lastTopic"));
                        merchant.setNewGoods(aData.getString("newGoods"));
//                        Intent intent = new Intent();
//                        intent.setClass(MainActivity.this, MerchantItemActivity.class);
//                        Bundle mBundle = new Bundle();
//                        mBundle.putSerializable("Merchant", merchant);
//                        intent.putExtras(mBundle);
//                        intent.putExtra("shopId", shopId);
//                        intent.putExtra("payType","2");
//                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, MainActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),MainActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MainActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId",shopId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}
